import React, { useEffect, useState } from 'react';
import { Table, message, Badge } from 'antd';
import styles from './TemplateApprove.less';
import TableFilter from '../../../../../../components/tableFilter';
import {
  getTemplateOwnerDept,
  getTemplateToDeal
} from '../../../../../messageManager/services/messageTemplateApi';

function TemplateApprove(props) {
  const {
    getColumnSearchProps,
    timeCreateTo,
    timeCreateEnd,
    sourceName,
    history,
    beforeNavigate,
  } = props;
  const [data, setData] = useState([]);
  const [deptList, setDeptList] = useState([]);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [ascOrDesc, setAscOrDesc] = useState('DESC'); // 升序/降序
  const [auditStatus, setAuditStatus] = useState(); // 审核状态筛选条件
  const [ownerDeptName, setOwnerDeptName] = useState(); // 归属部门筛选条件
  const [templateType, setTemplateType] = useState(); // 模板类型筛选条件

  const fetchListData = page => {
    const params = {
      auditStatus,
      templateName: sourceName,
      beginTime: timeCreateTo,
      endTime: timeCreateEnd,
      pageNum: page || pageNum,
      pageSize,
      orderBy: ascOrDesc,
      templateType,
      ownerDept: ownerDeptName
    };
    getTemplateToDeal(params).then(res => {
      if (res.success) {
        setData(res.datas);
        setTotal(res.totalCount);
      } else {
        message.error(res.errMsg);
      }
    });
  };
  useEffect(() => {
    fetchListData(1);
  }, [sourceName, timeCreateTo, timeCreateEnd]);
  useEffect(() => {
    fetchListData();
  }, [pageNum, pageSize, ascOrDesc, auditStatus, ownerDeptName, templateType]);
  useEffect(() => {
    getTemplateOwnerDept({}).then(res => {
      if (res.success) {
        const deptFilter = (res.datas || []).map(item => ({
          text: item.ownerDeptName,
          value: item.ownerDept
        }));
        setDeptList(deptFilter);
      } else {
        message.error(res.errMsg);
      }
    });
  }, []);

  const render = text => (text ? <span title={text}>{text}</span> : '-');
  const columns = [
    {
      title: '模板ID',
      dataIndex: 'templateId',
      render
    },
    {
      title: '模板名称',
      dataIndex: 'name',
      render
    },
    {
      title: '模板类型',
      dataIndex: 'type',
      filters: [
        {
          text: '短信模板',
          value: 2
        },
        {
          text: 'APP模板',
          value: 1
        }
      ],
      filterMultiple: false,
      render: text => <span>{text === 1 ? 'APP模板' : '短信模板'}</span>
    },
    {
      title: '使用场景',
      dataIndex: 'description',
      render
    },
    // {
    //   title: '模板标题',
    //   dataIndex: 'title',
    //   render,
    // },
    {
      title: '管理员',
      dataIndex: 'owner',
      render
    },
    {
      title: '归属部门',
      dataIndex: 'ownerDeptName',
      ...getColumnSearchProps(deptList),
      render
    },
    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      filters: [
        {
          text: '已通过',
          value: '1'
        },
        {
          text: '待审核',
          value: '0'
        },
        {
          text: '未通过',
          value: '-1'
        }
      ],
      filterMultiple: false,
      render: text => {
        let res;
        switch (text) {
          case 1:
            res = <Badge status='success' text='已通过' />;
            break;
          case 0:
            res = <Badge status='warning' text='待审核' />;
            break;
          case -1:
            res = <Badge status='warning' text='未通过' />;
            break;
          default:
            res = '';
        }
        return res;
      }
    },
    {
      title: '提交时间',
      dataIndex: 'timeCreate',
      width: 200,
      sorter: true,
      defaultSortOrder: 'descend',
      render
    },
    {
      title: '审核时间',
      dataIndex: 'timeHandle',
      width: 200,
      render
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 100,
      fixed: 'right',
      render: (text, record) => {
        const pathname =
          '/systemManager/systemMessage/messageBacklog/approveDetail?';
        const query = `templateId=${record.templateId}&pendingEventId=${record.pendingEventId}&specificEventId=${record.specificEventId}`;
        return (
          <a
            onClick={() => {
              if (beforeNavigate) {
                beforeNavigate();
              }
              history.push(pathname + query);
            }}
          >
            {record.auditStatus === 0 ? '审批' : '查看详情'}
          </a>
        );
      }
    }
  ];

  const handlePageChange = page => {
    setPageNum(page);
  };
  const handlePageSizeChange = (current, size) => {
    setPageSize(size);
    setPageNum(1);
  };
  const handleFilter = (pagination, filters, sorter) => {
    setOwnerDeptName(filters.ownerDeptName && filters.ownerDeptName[0]);
    setTemplateType(filters.type && filters.type[0]);
    setAuditStatus(filters.auditStatus && filters.auditStatus[0]);
    if (sorter.order) {
      setAscOrDesc(sorter.order === 'ascend' ? 'ASC' : 'DESC');
    } else {
      setAscOrDesc();
    }
  };

  return (
    <Table
      style={{ background: '#fff' }}
      className={styles.root}
      columns={columns}
      dataSource={data}
      scroll={data && data.length === 0 ? { x: false } : { x: 1500 }}
      rowKey='pendingEventId'
      onChange={handleFilter}
      pagination={{
        current: pageNum,
        pageSize,
        showSizeChanger: true,
        showQuickJumper: true,
        total,
        onChange: handlePageChange,
        onShowSizeChange: handlePageSizeChange,
        showTotal: () => `共有${total}条`
      }}
    />
  );
}

export default TableFilter(TemplateApprove);
